import { useStore } from 'vuex'
import { computed } from 'vue'
import _ from 'lodash'

/**
 * 判断值是否为空
 * @param data
 * @returns {boolean}
 */
export const isEmpty = (data) => {
  if (_.isNil(data)) return true

  const isCommonTypes = _.isString(data) || _.isObject(data) || _.isArray(data) || _.isSet(data)
  if (isCommonTypes) return _.isEmpty(data)

  return false
}

/**
 * 传入object,筛选空值的key后,返回筛选后的object
 * @param object
 * @returns {{}}
 */
export const filterEmptyByObject = (object = {}) => {
  // 判断传入的是否为对象类型
  const isObj = _.isObject(object)
  if (!isObj) {
    console.warn(`传入的值不是对象,不能做筛选处理`)
    return object
  }

  // 判断是否为空对象
  const isEmptyObj = _.isEmpty(object)
  if (isEmptyObj) {
    return {}
  }

  return _.keys(object).reduce((returnObj, key) => {
    let value = object[key]
    if (!isEmpty(value)) {
      // 判断如果是对象,则需要递归处理对象
      _.isObject(value) && (value = filterEmptyByObject(value))
      returnObj[key] = _.cloneDeep(value)
    }
    return returnObj
  }, {})
}

/**
 * 判断按钮是否有权限
 * @param btnCode
 * @returns {boolean}
 */
export const btnIsPowerByCode = btnCode => {
  const store = useStore()
  const powers = computed(() => store.getters.power)
  return powers.value.includes(btnCode)
}

/** 生产环境 */
export const isNotProduction = () => {
  return process.env.NODE_ENV !== 'production'
}

/** 聚合导入 */
export const getModule = context => {
  return context.keys().reduce((modules, key) => {
    return {
      ...modules,
      ...context(key).default
    }
  }, {})
}

/**
 * file对象转换base64
 * @param file
 * @returns {Promise<unknown>}
 */
export const getBase64 = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

/**
 * 生成随机id
 * @param {*} length
 * @param {*} chars
 */
export const uuid = (length, chars) => {
  chars = chars || '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  length = length || 8
  let result = ''
  for (let i = length; i > 0; --i)
    result += chars[Math.floor(Math.random() * chars.length)]
  return result
}

/**
 * 
 * 通过url下载图片
*/
export const downloadIamge = (imgsrc, name) => {
  let image = new Image();
  // 解决跨域 Canvas 污染问题
  image.setAttribute("crossOrigin", "anonymous");
  image.onload = function() {
    let canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    let context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, image.width, image.height);
    let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
    let a = document.createElement("a"); // 生成一个a元素
    a.download = name || '二维码'; // 设置图片名称
    a.href = url; // 将生成的URL设置为a.href属性
    a.click()
  }
  image.src = imgsrc;
}